package com.xgll.modules.api.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xgll.common.annotation.IgnoreAuth;
import com.xgll.common.utils.ApiBaseAction;
import com.xgll.common.utils.CharUtil;
import com.xgll.common.utils.R;
import com.xgll.common.utils.sms.SmsAlidayu;
import com.xgll.modules.api.annotation.LoginUser;
import com.xgll.modules.api.entity.QuestionVo;
import com.xgll.modules.api.entity.SmsLogVo;
import com.xgll.modules.api.entity.UserVo;
import com.xgll.modules.api.service.ApiUserQuestionService;
import com.xgll.modules.api.service.ApiUserService;

import net.sf.json.JSONObject;

/**
 * 作者: @author blowfish <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    @Autowired
    private ApiUserService userService;
    
    @Autowired
    private ApiUserQuestionService questionService;

    /**
     * 获取用户信息
     */
    @IgnoreAuth
    @RequestMapping("info")
    public Object info(HttpSession session) {        
        UserVo user = (UserVo)session.getAttribute("loginUser");
        //user.setPassword("");
        return user;
    }

    /**
     * 保存用户头像
     */
    @RequestMapping("saveAvatar")
    public Object saveAvatar(@LoginUser UserVo loginUser, String avatar) {
        return null;
    }

    /**
     * 发送短信
     */
    @RequestMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String phone = jsonParams.getString("phone");
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(4);
        String smsTemplateCode = "SMS_94340007";
        String msgContent = "您的验证码是：" + sms_code + "，请在页面中提交验证码完成验证。";
        String param = "{\"code\":\"" + sms_code + "\"}";
        // 发送短信
//        String rpt = "0";
        String rpt = SmsAlidayu.sendTplShortMessage(param, phone, smsTemplateCode);
        if (rpt == null || rpt.equals("0") == false) {
            return toResponsFail("短信发送失败");
        } else {
            smsLogVo = new SmsLogVo();
            smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
            smsLogVo.setUser_id(loginUser.getUserId());
            smsLogVo.setPhone(phone);
            smsLogVo.setSms_code(sms_code);
            smsLogVo.setSms_text(msgContent);
            userService.saveSmsCodeLog(smsLogVo);
            return toResponsSuccess("短信发送成功");
        }
    }

    /**
     * 获取当前会员等级
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("getUserLevel")
    public Object getUserLevel(@LoginUser UserVo loginUser) {
        String userLevel = userService.getUserLevel(loginUser);
        return toResponsSuccess(userLevel);
    }
    /**
     * 修改密码
     * @param session
     * @param oldpass
     * @param newpass
     * @return
     */
    @IgnoreAuth
    @RequestMapping("modifypassword")
    public Object updatePassword(HttpSession session,@RequestParam("oldpass") String oldpass,@RequestParam("newpass") String newpass){
    	UserVo user=(UserVo)session.getAttribute("loginUser");
    	if(!user.getPassword().equals(oldpass)){
    		System.out.println(!user.getPassword().equals(oldpass));
    		return R.error("原密码不正确！");
    	}
    	user.setPassword(newpass);
    	userService.update(user);
    	return R.ok("密码修改成功！");
    }
   
  //更新用户信息
    @IgnoreAuth
    @RequestMapping("modifyupdate")
    public Object updateUserInfo(UserVo loginUser){
    	userService.update(loginUser);
    	return R.ok("修改成功！");
    }
    
  //提交安全问题
    @IgnoreAuth
    @RequestMapping("modifyquestion")
    public Object saveQuestions(HttpServletRequest request,HttpSession session)
    {
    	try {
			QuestionVo q1 = new QuestionVo();
			QuestionVo q2 = new QuestionVo();
			q1.setUser_id(Long.valueOf(request.getParameter("user_id")));
			q2.setUser_id(Long.valueOf(request.getParameter("user_id")));
			q1.setQuestion(request.getParameter("question1"));
			q1.setAnswer(request.getParameter("answer1"));
			q2.setQuestion(request.getParameter("question2"));
			q2.setAnswer(request.getParameter("answer2"));
			questionService.save(q1);
			questionService.save(q2);
			return R.ok("保存成功");
		} catch (Exception e) {
			return R.ok("保存失败");
		}
    }
    
    
}